package com.d2rabbit.exception.config;


import cn.hutool.log.StaticLog;
import com.d2rabbit.exception.exception.CustomerException;
import com.d2rabbit.exception.exception.DefaultException;
import com.d2rabbit.exception.exception.ParameterCheckException;
import com.d2rabbit.exception.exception.handler.ExceptionResult;
import com.d2rabbit.exception.exception.handler.ResultHandler;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
* 全局异常
*
* */
@ControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 在当前类每个方法进入之前触发的操作
     */
    @ModelAttribute
    public void get(HttpServletRequest request) throws IOException {

    }


    @ResponseBody
    @ExceptionHandler({CustomerException.class, DefaultException.class, ParameterCheckException.class,Exception.class})
    public ExceptionResult handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        //异常信息查看
        StaticLog.info("————————————————————————错误信息抛出————————————————");
        StaticLog.error(e);

        if (e instanceof DefaultException) {
            DefaultException dex = (DefaultException) e;
            return ResultHandler.returnResult(dex.getExceptionCode(),dex.getMessage(),false);
        }else if (e instanceof ParameterCheckException) {
            ParameterCheckException pce = (ParameterCheckException) e;
            return ResultHandler.returnResult(pce.getExceptionCode(),pce.getMessage());
        }else if (e instanceof CustomerException) {
            CustomerException cex = (CustomerException) e;
            return ResultHandler.returnResult(cex.getExceptionCode(),cex.getMessage());
        }else if (e instanceof RuntimeException) {
            RuntimeException rex = (RuntimeException) e;
            return ResultHandler.returnResult(rex.getMessage());
        }else{
            return ResultHandler.returnResult(e.getMessage());
        }
        // 不同异常返回不同状态码
    }
}
